<?php
/**
 * Created by PhpStorm.
 * User: jack
 * Date: 2018-11-29
 * Time: 17:33
 */

namespace App\Services;

use Illuminate\Support\Facades\Cache;


class CacheService
{
    private $prefix    = 'xiaokedou';//缓存前缀
    private $version   = '1.0';//缓存版本
    private $openCache = false;//是否开启缓存

    public function __construct()
    {
        $this->openCache = env('REDIS_CACHE_OPEN', false);
    }

    /**
     * 构建缓存key
     * @param $key
     * @return string
     */
    public function buildCacheKey($key)
    {
        return sprintf('%s_%s_', $this->prefix, $this->version) . $key;
    }

    /**
     * 自增
     * @param $key
     * @param $value
     * @return bool|int
     */
    public function increment($key, $value)
    {
        if (!$this->openCache){
            return false;
        }
        $res = Cache::has($this->buildCacheKey($key));
        if ($res === false){
            return false;
        }

        return Cache::increment($this->buildCacheKey($key), $value);
    }

    /**
     * 获取缓存
     * @param $key
     * @return bool|mixed
     */
    public function getCache($key)
    {
        if (!$this->openCache){
            return false;
        }
        $res = Cache::get($this->buildCacheKey($key));
        if ($res === null){
            return false;
        }

        return $res;
    }

    /**
     * 设置缓存
     * @param $key
     * @param $data
     * @param int $minutes
     * @return bool
     */
    public function setCache($key, $data, $minutes = 1)
    {
        if (!$this->openCache){
            return false;
        }
        $this->clearCache($key);

        return Cache::add($this->buildCacheKey($key), $data, $minutes);
    }

    /**
     * 设置永久缓存
     * @param $key
     * @param $data
     * @return bool
     */
    public function setForeverCache($key, $data)
    {
        if (!$this->openCache){
            return false;
        }
        $this->clearCache($key);
        Cache::forever($this->buildCacheKey($key), $data);
    }

    /**
     * 清除缓存
     * @param $key
     * @return bool
     */
    public function clearCache($key)
    {
        if (!$this->openCache){
            return true;
        }

        return Cache::forget($this->buildCacheKey($key));
    }


    /**
     * 地址key
     * @param $key
     * @return string
     */
    public function upgradeAddressSearchKey($key)
    {
        return sprintf('upgrade_address_search_%s', $key);
    }
}